package com.example.demo.sys.service.impl;

import com.example.demo.sys.common.BeanValidator;
import com.example.demo.sys.common.LevelUtil;
import com.example.demo.sys.common.UUIDUtil;
import com.example.demo.sys.mapper.SysDeptMapper;
import com.example.demo.sys.model.SysDept;
import com.example.demo.sys.param.DeptParam;
import com.example.demo.sys.service.SysDeptService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by 蔡超 on 2018/10/7.
 */
@Service
public class SysDeptServiceImpl implements SysDeptService {

    @Autowired
    private SysDeptMapper sysDeptMapper;


    @Override
    public String save(DeptParam deptParam) {
        BeanValidator.validateObject(deptParam);
        if(checkExist(deptParam.getParentid(),deptParam.getName())){
            //TODO 已经存在同名部门
            return null;
        }else{
            SysDept sysDept = SysDept.builder().name(deptParam.getName()).parentid(deptParam.getParentid())
                    .seq(deptParam.getSeq()).remarks(deptParam.getRemarks()).build();
//            sysDept.setLevel(LevelUtil.calculateLevel(getLevel(deptParam.getParentid()),deptParam.getName()));
            String id = UUIDUtil.createUUID();
            sysDept.setId(id);
            sysDept.setGmtCreate(new Date());
            sysDept.setCreateUser("system");
            sysDept.setOperateip("127.0.0.1");
            sysDeptMapper.insert(sysDept);
            return id;
        }
    }

    @Override
    public int update(DeptParam deptParam) {
        SysDept sysDept = new SysDept();
        BeanUtils.copyProperties(sysDept,deptParam);
        return sysDeptMapper.updateByPrimaryKey(sysDept);
    }

    /** 
    * @Description: 判断同一级部门是否出现名字相同
    * @Param:  
    * @return:  
    * @Author: 蔡超
    * @Date: 2018/10/7 9:08
    */
    private boolean checkExist(String parentId,String name){
        return true;
    }

    private int getLevel(String deptId){
        SysDept sysDept = sysDeptMapper.selectByPrimaryKey(deptId);
        if(sysDept == null){
            return 0;
        }else{
            return sysDept.getLevel();
        }
    }

}
